﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GoogleReaderToDelicious.Core.DTO;
using GoogleReaderToDelicious.Core.Helpers;
using GoogleReaderToDelicious.Core.Infrastructure;
using GoogleReaderToDelicious.Core.Model;
using GoogleReaderToDelicious.Core.Repositories;
using Newtonsoft.Json.Linq;

namespace GoogleReaderToDelicious.Core.Services
{
    //20-Nov-2011 Priyan R
    public class ExportService : ServiceBase
    {
        private ExportRepository _exportRepository;
        public ExportService()
            : base(DatabaseContext.Create())
        {
            _exportRepository = new ExportRepository(_context);
        }
        public void ImportToLocalDB(string path)
        {

            var notes = ParseGoogleReaderNotes(path);
            foreach (var note in notes)
            {
                var bookmark = new BookMark();
                bookmark.Id = Guid.NewGuid();
                bookmark.Title = note.Title;
                bookmark.Url = note.Url;
                bookmark.Comments = note.Comments;
                bookmark.Tags = note.Tags;
                bookmark.CreateDate = note.CreateDate;
                _context.Add(bookmark);
            }
            try
            {
                _context.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }
        }
        public void ExportToDelicious(string userName, string password,
                Guid bookMarkId)
        {
            var delicous = new DeliciousHelper();
            var title = "";
            var bookMark = _exportRepository.GetBookMarkById(bookMarkId);
            title = bookMark.Title;
            //delicous doesn't allow blank titles
            if (string.IsNullOrEmpty(title))
            {
                title = "[No Title]";
            }
            delicous.UserName = userName;
            delicous.Password = password;
            delicous.AddBookmark(title, bookMark.Url, bookMark.Tags, bookMark.CreateDate);
            bookMark.IsExported = true;
            _context.SaveChanges();

        }
        public BookMarkCountDetailsDTO GetBookMarkCountDetails()
        {
            return _exportRepository.GetBookMarkCountDetails();
        }
        public List<BookMark> GetBookMarksToExport()
        {
            return _exportRepository.GetBookMarksToExport();
        }

        public void DeleteAllImportedData()
        {
            _exportRepository.DeleteAllNotes();
        }
        private List<GoogleReaderNoteItemDTO> ParseGoogleReaderNotes(string path)
        {
            var ret = new List<GoogleReaderNoteItemDTO>();
            string jsonData = System.IO.File.ReadAllText(path, Encoding.UTF8);
            JObject json = JObject.Parse(jsonData);
            var items = (JArray)json["items"];
            var userIdString = ((string)json["id"]).Replace("/source/com.google/post", "");
            var tagStartString = userIdString + "/label/";
            Parallel.ForEach(items,
            (item) =>
            {

                var retItem = new GoogleReaderNoteItemDTO();
                var comments = ((JArray)item["comments"]);
                var categories = ((JArray)item["categories"]);
                //
                retItem.Title = ((string)item["title"]) ?? "";
                retItem.Url = (string)((JArray)item["alternate"])[0]["href"];
                if (comments.Count > 0)
                {
                    retItem.Comments = (string)comments[0] ?? "";
                }
                if (categories.Count > 0)
                {
                    var tags = categories.Where(p => ((string)p).StartsWith(tagStartString))
                        .Select(p => (string)p).ToList();
                    if (tags.Count > 0)
                    {
                        retItem.Tags = string.Join(",", tags.Select(p => p.Replace(tagStartString, "")));
                    }
                }
                retItem.CreateDate = AppUtility.ConvertFromUnixTimestamp(long.Parse(item["published"].ToString()));
                DateTime.SpecifyKind(retItem.CreateDate, DateTimeKind.Utc);
                lock (ret)
                {
                    ret.Add(retItem);
                }
            });
            ret = ret.OrderBy(p => p.CreateDate).ToList();
            return ret;
        }
    }
}
